import useTableList from '@/utils/useTableList';
import { PageContainer } from '@ant-design/pro-components';
import {
  Button,
  Checkbox,
  Col,
  Flex,
  Form,
  Image,
  Input,
  Modal,
  Row,
  Select,
  Space,
  Table,
  Tag,
  Upload,
} from 'antd';
import React, { useEffect, useState } from 'react';
import styles from './index.less';
import {
  CloudUploadOutlined,
  ExclamationCircleOutlined,
  ReloadOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import message from '@/utils/message';
import { editFileApi, fileUploadApi, getFileListApi } from '@/services/file';

const fileTypes: any[] = [
  {
    value: 0,
    label: '图片',
  },
  {
    value: 1,
    label: '文档',
  },
  {
    value: 2,
    label: '视频',
  },
  {
    value: 3,
    label: '压缩包',
  },
];

const sourceTypes: any[] = [
  {
    value: 0,
    label: '工厂图片',
  },
  {
    value: 1,
    label: '标签图片',
  },
  {
    value: 2,
    label: '其他',
  },
];

const File: React.FC = () => {
  const { loading, setLoading, form, datasource, page, pageSize, total, onFinish, onPageChange } =
    useTableList({ fetchApi: getFileListApi });
  const [editForm] = Form.useForm();
  const [currentData, setCurrentData] = useState<any>(null);

  useEffect(() => {
    if (currentData) {
      editForm.setFieldsValue(currentData);
    } else {
      editForm.resetFields();
    }
  }, [currentData]);

  const onCancel = () => {
    setCurrentData(null);
  };

  const onSave = async (v: any) => {
    setLoading(true);
    const data = new FormData();
    data.append('bindToSource', v.bindToSource);
    data.append('sourceType', v.sourceType);
    if (v.files && v.files.fileList.length > 0) {
      v.files.fileList.forEach((file: any) => {
        data.append('files', file.originFileObj);
      });
    }
    const { rsCode } = await fileUploadApi(data);
    setLoading(false);
    if (rsCode === '00000000') {
      message.success('保存成功');
      onCancel();
      onPageChange(page);
    }
  };

  const onOk = async () => {
    editForm
      .validateFields()
      .then((v: any) => {
        onSave(v);
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const changeStatus = (row: any) => {
    Modal.confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '确定要删除该文件吗？',
      okText: '确定',
      cancelText: '取消',
      centered: true,
      onOk: async () => {
        const { rsCode } = await editFileApi({
          id: row.id,
          status: 2,
        });
        if (rsCode === '00000000') {
          message.success('操作成功');
          onPageChange(page);
        }
      },
    });
  };

  const columns: ColumnsType<any> = [
    {
      title: '编号',
      dataIndex: 'id',
      key: 'id',
      width: 100,
    },
    {
      title: '文件名称',
      dataIndex: 'fileName',
      key: 'fileName',
    },
    {
      title: '预览',
      dataIndex: 'filePath',
      key: 'filePath',
      width: 200,
      render: (filePath, row) =>
        row.fileType === 0 ? <Image src={filePath} alt="file" width={'100%'} /> : '不支持预览',
    },
    {
      title: '文件类型',
      dataIndex: 'fileType',
      key: 'fileType',
      width: 150,
      render: (type: number) => {
        if (type === 0) {
          return <Tag color="blue">图片</Tag>;
        } else if (type === 1) {
          return <Tag>文档</Tag>;
        } else if (type === 2) {
          return <Tag color="orange">视频</Tag>;
        } else if (type === 3) {
          return <Tag color="purple">压缩包</Tag>;
        }
      },
    },
    {
      title: '来源类型',
      dataIndex: 'sourceType',
      key: 'sourceType',
      width: 150,
      render: (type: number) => {
        const item = sourceTypes.find((item) => item.value === type);
        if (item) {
          return item.label;
        }
        return '未知类型';
      },
    },
    {
      title: '文件大小',
      dataIndex: 'fileSize',
      key: 'fileSize',
      width: 150,
      render: (size: number) => {
        return `${(size / 1024).toFixed(2)} KB`;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 150,
      render: (status: number) => {
        if (status === 2) {
          return <Tag color="gray">已删除</Tag>;
        } else {
          return <Tag color="#87d068">正常</Tag>;
        }
      },
    },
    {
      title: '上传时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 200,
      render: (time: number) => {
        return dayjs(time * 1000).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 200,
      render: (time: number) => {
        return dayjs(time * 1000).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      width: 150,
      fixed: 'right',
      render: (_, row) => {
        return (
          <Space>
            <a href={row.filePath} download target="_blank" rel="noopener noreferrer">
              <Button type="primary" size="small">
                下载
              </Button>
            </a>
            {row.status === 1 && (
              <Button type="primary" size="small" danger onClick={() => changeStatus(row)}>
                删除
              </Button>
            )}
          </Space>
        );
      },
    },
  ];

  return (
    <PageContainer>
      <Row gutter={[30, 30]} style={{ padding: '15px 30px' }}>
        <div className={styles.search_box}>
          <Form
            form={form}
            onFinish={onFinish}
            onReset={() => onFinish({})}
            labelCol={{
              span: 5,
            }}
            style={{ width: '100%' }}
          >
            <Row gutter={[20, 20]}>
              <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={6}>
                <Form.Item label="文件名称" name="fileName">
                  <Input placeholder="请输入文件名称" />
                </Form.Item>
              </Col>
              <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={6}>
                <Form.Item label="文件类型" name="fileType">
                  <Select options={fileTypes} placeholder="请选择" allowClear />
                </Form.Item>
              </Col>
              <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={6}>
                <Form.Item label="文件来源" name="sourceType">
                  <Select options={sourceTypes} placeholder="请选择" allowClear />
                </Form.Item>
              </Col>
              <Col xs={24} sm={24} md={12} lg={12} xl={24} xxl={6}>
                <Flex align="center" justify="flex-end" gap={15}>
                  <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                    查询
                  </Button>
                  <Button htmlType="reset" icon={<ReloadOutlined />}>
                    重置
                  </Button>
                  <Button
                    color="primary"
                    variant="outlined"
                    icon={<CloudUploadOutlined />}
                    onClick={() => setCurrentData({})}
                  >
                    上传文件
                  </Button>
                </Flex>
              </Col>
            </Row>
          </Form>
        </div>
        <div className={styles.table_box}>
          <Table
            columns={columns}
            dataSource={datasource}
            loading={loading}
            rowKey="id"
            scroll={{ x: 1800 }}
            pagination={{
              current: page,
              pageSize: pageSize,
              total: total,
              showSizeChanger: false,
              showQuickJumper: true,
              onChange: onPageChange,
              showTotal: (total) => `共 ${total} 条数据`,
            }}
          />
        </div>
      </Row>
      <Modal
        title="上传文件"
        centered
        width={600}
        open={!!currentData}
        onCancel={onCancel}
        onOk={onOk}
        okButtonProps={{ loading }}
      >
        <Form
          form={editForm}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 16 }}
          style={{ padding: '20px 0' }}
        >
          <Form.Item
            label="来源类型"
            name="sourceType"
            rules={[{ required: true, message: '请选择来源类型' }]}
          >
            <Select placeholder="请选择来源类型" options={sourceTypes} />
          </Form.Item>
          <Form.Item
            label="是否绑定"
            name="bindToSource"
            valuePropName="checked"
            initialValue={false}
          >
            <Checkbox>上传后自动绑定到工厂信息上</Checkbox>
          </Form.Item>
          <Form.Item label="文件" rules={[{ required: true, message: '请选择文件' }]} name="files">
            <Upload listType="picture" multiple={true} beforeUpload={() => false}>
              <Button type="primary">选择文件</Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default File;
